package com.lmt.service.impl;

import com.lmt.base.BaseService;
import com.lmt.base.ResultData;
import com.lmt.entity.Dissertation;
import com.lmt.entity.search.DissertationSearch;
import com.lmt.repository.DissertationRepository;
import com.lmt.service.DissertationService;
import com.lmt.util.RedisCacheUtil;
import com.lmt.util.ResultUtil;
import com.lmt.util.SystemConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * Date 2018/07/17
 *
 * @author MT-Lin
 */
@Service("DissertationServiceImpl")
public class DissertationServiceImpl extends BaseService implements DissertationService {

	private final DissertationRepository dissertationRepository;

	private final RedisCacheUtil redisCacheUtil;

	@Autowired
	public DissertationServiceImpl(DissertationRepository dissertationRepository, RedisCacheUtil redisCacheUtil) {
		this.dissertationRepository = dissertationRepository;
		this.redisCacheUtil = redisCacheUtil;
	}

	@Override
	public ResultData save(Dissertation dissertation) {
		Dissertation exist = this.dissertationRepository.findByClassifyIdAndDesignation(dissertation.getClassifyId(),
				dissertation.getDesignation());
		if (null != exist) {
			return ResultUtil.newFail("该分类下该专题名称已存在");
		}
		dissertation.setCreator(redisCacheUtil.getUserName(dissertation));
		this.dissertationRepository.save(dissertation);
		if (null == dissertation.getId()) {
			return ResultUtil.newFail("添加专题失败");
		}
		return ResultUtil.newSuccess("成功添加专题");
	}

	@Override
	public ResultData search(DissertationSearch dissertationSearch) {
		StringBuffer sql = new StringBuffer();
		sql.append("SELECT d.id, d.designation, d.description, d.creator, ");
		sql.append("d.collection_num AS collectionNum, ");
		sql.append("d.document_num AS documentNum, ");
		sql.append("d.download_num AS downloadNum, ");
		sql.append("d.gmt_create AS gmtCreate, ");
		sql.append("(SELECT c.designation FROM classify AS c WHERE c.id = d.classify_id) ");
		sql.append("AS classify, ");
		sql.append("(SELECT td.designation FROM dissertation AS td WHERE td.id = d.parent_id) ");
		sql.append("AS parent ");
		sql.append("FROM dissertation AS d WHERE 1 = 1 ");
		if (!StringUtils.isEmpty(dissertationSearch.getKeyword())) {
			sql.append("AND (d.designation LIKE ? OR d.description LIKE ? OR d.creator LIKE ?) ");
			dissertationSearch.setParamsCount(3);
		}
		Map<String, Object> result = this.paginationSearch(sql, dissertationSearch);
		return ResultUtil.newSuccess("查询专题成功", result);
	}

	@Override
	public ResultData findOneById(String id) {
		Optional<Dissertation> result = this.dissertationRepository.findById(id);
		if (!result.isPresent()) {
			return ResultUtil.newFail("该专题不存在");
		}
		return ResultUtil.newSuccess("查询专题成功", result);
	}

	@Override
	public ResultData delete(List<Dissertation> dissertations) {
		for (Dissertation dissertation : dissertations) {
			this.dissertationRepository.deleteById(dissertation.getId());
		}
		return ResultUtil.newSuccess("删除成功");
	}

	@Override
	public ResultData update(Dissertation dissertation) {
		Optional<Dissertation> old = this.dissertationRepository.findById(dissertation.getId());
		if (!old.isPresent()) {
			ResultUtil.newFail("更新的专题不存在");
		}
		this.dissertationRepository.save(dissertation);
		return ResultUtil.newSuccess("专题更新成功");
	}

	@Override
	public ResultData getParentTree() {
		List result = this.getTreeOptions();
		return ResultUtil.newSuccess("父主题树选项获取成功", result);
	}

	@Override
	public ResultData getHasResourceDissertationIdsGroup() {
		List<Dissertation> all = this.dissertationRepository.findAll();
		Map<String, Dissertation> firstLevel = new HashMap<>(all.size());
		List<Dissertation> children = new ArrayList<>();
		Map<String, List<Object>> temp = new HashMap<>(all.size());
		for (Dissertation dissertation : all) {
			if (null == dissertation.getParentId()) {
				firstLevel.put(dissertation.getId(), dissertation);
				temp.put(dissertation.getId(), new ArrayList<>());
				temp.get(dissertation.getId()).add(dissertation.getId());
			} else if (temp.get(dissertation.getParentId()) != null) {
				temp.get(dissertation.getParentId()).add(dissertation.getId());
			} else {
				children.add(dissertation);
			}
		}
		for (Dissertation child : children) {
			temp.get(child.getParentId()).add(child.getId());
		}
		Map<Dissertation, List<Object>> result = new HashMap<>(all.size());
		for (String id : firstLevel.keySet()) {
			result.put(firstLevel.get(id), temp.get(id));
		}
		return ResultUtil.newSuccess("查询成功", result);
	}

	private List getTreeOptions() {
		List<Map<String, Object>> result = new ArrayList<>();
		List<Dissertation> firstLevel = new ArrayList<>();
		List<Dissertation> children = new ArrayList<>();
		List<Dissertation> all = this.dissertationRepository.findAll();
		Map<String, Map<String, Object>> temp = new HashMap<>(all.size());
		for (Dissertation dissertation : all) {
			Map<String, Object> tempOption = new HashMap<>(4);
			tempOption.put(SystemConstant.PROPS_ID, dissertation.getId());
			tempOption.put(SystemConstant.PROPS_LABEL, dissertation.getDesignation());
			tempOption.put("classifyId", dissertation.getClassifyId());
			tempOption.put(SystemConstant.PROPS_CHILDREN, new ArrayList<>());
			temp.put(dissertation.getId(), tempOption);
			if (null == dissertation.getParentId()) {
				firstLevel.add(dissertation);
			} else {
				children.add(dissertation);
			}
		}
		for (Dissertation child : children) {
			//noinspection unchecked
			((List) temp.get(child.getParentId()).get(SystemConstant.PROPS_CHILDREN)).add(temp.get(child.getId()));
		}
		for (Dissertation dissertation : firstLevel) {
			result.add(temp.get(dissertation.getId()));
		}
		return result;
	}

}
